import {useEffect, useState} from 'react';
import {Menu} from 'antd'
import {useLocation, useNavigate} from 'react-router-dom';
import {getMenus,getCurrentMenus, IconMap} from '@/utils/Menu.ts'
import {useSelector} from "react-redux";


const Sidebar = () => {
    let openKeys2 = []
    const getFatherKey = () => {
        const item = getCurrentMenus(getMenus(), location.pathname || '/')
        if (item) {
            openKeys2 = [item.fatherkey]
        }
    }
    const MenuIcon = (imgSrc: string) => {
            return <img
                style={{width: 20, height: 20, marginRight: 10}}
                src={imgSrc}
                alt="icon"
            />
    }
    const {collapsed} = useSelector(state => state.userSlice)
    const [items, setItems] = useState([]);
    const location = useLocation();
    getFatherKey()
    const navigate = useNavigate();
    const [current, setCurrent] = useState(location.pathname);
    const [openKeys, setOpenKeys] = useState(openKeys2);
    useEffect(() => {
        const list = getMenus()
        list.forEach(async item =>{
            // MenuIcon(IconMap[item.icon]).then(res=>{
            //     console.log(res,'res')
            // })
            item.icon = MenuIcon(IconMap[item.icon])
        })
        setItems(list)
    }, []);
    // 确保路径匹配根路由
    useEffect(() => {
        setCurrent(location.pathname || '/');
    }, [location.pathname]);

    const onSelect = ({key}) => {
        setCurrent(key)
        navigate(key);
    }


    return (
        <div className="l-sidebar">
            <img width={collapsed?60:125} src="https://sqzbx-test.etib.cn/homePage/public/img/LOGO@2x.c1695674.png" />
            <Menu
                selectedKeys={[current]}
                mode="inline"
                items={items}
                // style={{width: 256}}
                onSelect={onSelect}
                defaultOpenKeys={openKeys}
                inlineCollapsed={collapsed}
            />
        </div>

    );
};

export default Sidebar;